package tr.edu.metu.is550.isell.activity;

import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import tr.edu.metu.is550.isell.utils.CryptoUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ListCommentsActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] values = retrieveAllComments(PreferenceManager.getDefaultSharedPreferences(this));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

    private String[] retrieveAllComments(SharedPreferences sp) {
        String[] comments = null;
        String propertyId = (String) getIntent().getExtras().get("propertyId");
        String serverURL = sp.getString("pref_dialog", "NULL");
        DefaultHttpClient client = new DefaultHttpClient();
        String uri = serverURL + "/property/" + propertyId + "/comment";
        HttpGet httpGet = new HttpGet(uri);
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), sp.getString("userName", "") + ":" + sp.getString("password", "")));

        try {

            HttpResponse response = client.execute(httpGet);
            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new RuntimeException("An error occured during retrieving comments!");
            } else {
                HttpEntity entity = response.getEntity();
                String result = convertStreamToString(entity.getContent());
                JSONObject jsonObject = new JSONObject(result);
                JSONObject properties = jsonObject.getJSONObject("");
                JSONArray commentArray = properties.getJSONArray("comments");
                comments = new String[commentArray.length()];
                if (commentArray.length() == 0) {
                    Toast.makeText(getApplicationContext(), "No comments found!", Toast.LENGTH_LONG).show();
                } else {
                    for (int i = 0; i < commentArray.length(); i++) {
                        comments[i] = commentArray.getJSONObject(i).getString("user") + " => " + commentArray.getJSONObject(i).getString("comment");
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return comments;

    }


    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        String item = (String) getListAdapter().getItem(position);
        Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
    }
}
